import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:my_shop/cache_event_identification.dart';
import 'package:my_shop/cart/my_cart_page.dart';
import 'package:my_shop/index/good_list_page.dart';
import 'package:my_shop/load_my_goods.dart';
import 'package:my_shop/my/my_page.dart';
import 'package:my_shop/order_list/order_list_page.dart';

class HomePage extends StatefulWidget {
  const HomePage({
    super.key,
  });

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  /// Since the home page is never destroyed or reinitialized,
  /// the list of saved usernames and passwords is saved here
  /// Initializes a list of registered accounts
  List<UserModel> allAccount = [];

  late List<Widget> _pageList;

  /// Navigation bar name
  final List<String> _appBarTitles = ['index', 'recommend', 'cart', 'my'];

  /// Navigation bar icon
  List<BottomNavigationBarItem> items = [];

  /// Paging controller
  final PageController _pageController = PageController();

  late Color mainColor;

  @override
  void initState() {
    super.initState();
    List<GoodModel> allGoodsList = SpUtil.getObjList<GoodModel>(
            Constant.allGoodsList,
            (v) => GoodModel.fromJson(v as Map<String, dynamic>)) ??
        [];
    bool? isLoginStatus = SpUtil.getBool(Constant.isLoginStatus);
    // If it exists in the cache, the cache is used, if not, it is restored to the initial value
    if (allGoodsList.isEmpty) {
      SpUtil.putObjectList(Constant.allGoodsList, MyAllGoods.allGoodsList);
    }
    if (isLoginStatus == null) {
      SpUtil.putObject(Constant.allGoodsList, false);
    }
    if (SpUtil.getInt(Constant.mainColor) == 0) {
      mainColor = MyColor.mainColor;
      SpUtil.putInt(Constant.mainColor, mainColor.value);
    } else {
      mainColor = Color(SpUtil.getInt(Constant.mainColor)!);
    }
    _pageList = [
      GoodListPage(jumpMyPage),
      const OrderListPage(),
      const CartPage(),
      const MyPage(),
    ];
  }

  /// can't shop when you are not logged in.
  /// The page jumps to my page
  void jumpMyPage() {
    _pageController.jumpToPage(3);
    setState(() {
      currentIndex = 3;
    });
  }

  /// ADAPTS photo width to the screen
  static const double _imageSize = 25.0;

  /// ICONS for selected and unselected states
  static List<List<dynamic>> tabImages = [
    [
      Image.asset('assets/images/home/icon_home_unselect.png',
          width: _imageSize),
      Image.asset('assets/images/home/icon_home_select.png', width: _imageSize)
    ],
    [
      Image.asset('assets/images/home/icon_order_unselect.png',
          width: _imageSize),
      Image.asset('assets/images/home/icon_order_select.png',
          width: _imageSize),
    ],
    [
      Image.asset('assets/images/home/icon_shopping_unselect.png',
          width: _imageSize),
      Image.asset('assets/images/home/icon_shopping_select.png',
          width: _imageSize),
    ],
    [
      Image.asset('assets/images/home/icon_me_unselect.png', width: _imageSize),
      Image.asset('assets/images/home/icon_me_select.png', width: _imageSize),
    ]
  ];

  List<BottomNavigationBarItem> _buildBottomNavigationBarItem() {
    items = List.generate(4, (i) {
      return BottomNavigationBarItem(
        icon: tabImages[i][0],
        activeIcon: tabImages[i][1],
        label: _appBarTitles[i],
      );
    });
    return items;
  }

  int currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        backgroundColor: Colors.white,
        type: BottomNavigationBarType.fixed,
        items: _buildBottomNavigationBarItem(),
        elevation: 5.0,
        iconSize: 20.0,
        selectedFontSize: 10,
        unselectedFontSize: 10,
        currentIndex: currentIndex,
        unselectedItemColor: Colors.black,
        selectedItemColor: const Color(0xFFFF8547),
        onTap: (index) {
          if (index == 1 || index == 2) {
            if (!(SpUtil.getBool(Constant.isLoginStatus) ?? false)) {
              Fluttertoast.showToast(
                  msg:
                      'Currently out of the login state, please login and try again');
              return jumpMyPage();
            }
          }
          _pageController.jumpToPage(index);
          setState(() {
            currentIndex = index;
          });
        },
      ),
      body: PageView(
        physics: const NeverScrollableScrollPhysics(),
        controller: _pageController,
        children: _pageList,
      ),
    );
  }
}
